import { getSnInfoById } from '../../api/myEquipment';
import mqttHandle from '../../utils/mqttHandler';

const MqttClient = new mqttHandle().createConnect()
const state = {
	snInfo: {
		id: '',
		avatar: '',
		name: '',
		value: '',
	},
	isOnline: 2
}

const mutations = {
	SETSNINFO(state, snInfo) {
		state.snInfo = snInfo
		uni.setStorageSync('snId', snInfo.id)
	},
	SETONLINE(state, status) {
		state.isOnline = status
	}
}

const actions = {
	getSnOnline({ state, commit }) {
		var topic = 'MQTT/T/UPDATE_DEVICE_INFO/SN_' + state.snInfo.value
		//配置topic
		MqttClient.subscribe(topic, {
			qos: 0
		}, (error, res) => {
			if (error) {
				console.log("Subscribe to topics error", error);
			}
		});
		MqttClient.on("message", (topic, message) => {
			try {
				let status = ""
				if (message.toString().length === 1) {
					status = message.toString() // status 1: 在线 2：离线
				} else {
					let jsonStatus = JSON.parse(message.toString())
					status = jsonStatus.message
				}
				commit('SETONLINE', status)
			} catch (error) {}
		});
	},
	getSnInfoById({ state, commit }) {
			return new Promise((resolve, reject) => {
				getSnInfoById({
					id: state.snInfo.id,
				}).then(res => {
					if (res.code === 200) {
						commit('SETSNINFO', res.data);
						resolve(res);
					} else {
						reject(new Error('Failed to fetch SN info'));
					}
				}).catch(error => {
					console.log("这是设置错误", error);
					reject(error);
				});
			});
		}
}

export default {
	state,
	mutations,
	actions
};